<?php
/**
 * Controller_Admin_Product
 *
 * Класс Controller_Admin_Product отвечает за обработку админских страниц товаров
 *
 * @author Mike
 */
class Controller_Admin_Product extends Controller_Admin {

	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		if(!User_Seance::isAdmin()) throw new Exception('', 403);
		switch ($this->arrRequest[2]) {
			case '':
				$this->actionProductsList();
				break;
			case 'add':
				$this->actionAdd();
				break;
			case 'edit':
				$objProduct = new Product(intval($this->arrRequest[3]));
				if(!$objProduct->id) throw new Exception('', 404);
				$this->actionEdit($objProduct);
				break;
			case 'gallery':
				$objProduct = new Product(intval($this->arrRequest[3]));
				if(!$objProduct->id) throw new Exception('', 404);
				$this->actionGallery($objProduct);
				break;
			default: throw new Exception('', 404);
		}
	}

	/**
	 * Выводит свписок товаров
	 *
	 */
	public function actionProductsList() {
		$objProduct = new Product();
		$arrProducts = $objProduct->find('all', array('order' => '`product`.`product_name`'));

		$this->title = 'Товары';
		$this->pageHead = $this->title . '(<a href="' . W_ADMIN . 'products/add">Добавить</a>)';
		
		$this->showHeader();
			View_Product::showAdminList($arrProducts);
		$this->showFooter();
	}
	
	/**
	 * Добавление товара
	 *
	 */
	public function actionAdd() {
		if (isset($_POST['Product'])) {
			$objProduct = new Product($_POST['Product']);
			if ($objProduct->save()) User_Seance::moveTo(W_ADMIN . 'products');
		}
		else $objProduct = new Product();
	
		$this->title = $this->pageHead = 'Добавление товара';
			
		$this->showHeader();
			View_Product::showEditForm($objProduct);
		$this->showFooter();
	}
	
	/**
	 * Редактирование товара
	 *
	 * @param Product $objProduct - объект товара
	 */
	public function actionEdit(Product $objProduct) {
		if (isset($_POST['Product'])) {
			$objProduct = new Product($_POST['Product']);
			if ($objProduct->save()) User_Seance::moveTo(W_ADMIN . 'products');
		}
	
		$this->title = $this->pageHead = 'Редактирование товара';
			
		$this->showHeader();
			View_Product::showEditForm($objProduct);
		$this->showFooter();
	}
	
	/**
	 * Редактирование фотографий
	 *
	 * @param Product $objProduct - объект товара
	 */
	public function actionGallery(Product $objProduct) {
		if (!empty($_FILES)) {
			Photo::savePhotosFromFiles($objProduct->id, Product::$idEssenceType);
			$objProduct = new Product($objProduct->id);
		}
		
		$arrPhotos = $objProduct->getPhotosIds();
		
		$this->title = $this->pageHead = 'Фотографии товара';
		$this->bodyAttr = 'photos-edit';
			
		$this->showHeader();
			View_Product::showProductPhotos($arrPhotos, $objProduct->getField('ID_photo'));
			View_Product::showGalleryForm($objProduct);
		$this->showFooter();
	}
}